Skip to content

Gemma fix - #331

Closed
exadeci wants to merge 7 commits into
straff2002:mainfrom
exadeci:gemma_fix
Closed

exadeci wants to merge 7 commits into
straff2002:mainfrom
exadeci:gemma_fix

Conversation

@exadeci

@exadeci exadeci commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

- Updated `mlx-swift-lm` dependency to a specific revision to address issues with vision model compatibility.
- Modified localization strings in `Localizable.xcstrings` to include new entries and improve clarity.
- Adjusted notes in `LocalLLMService` to reflect changes in model capabilities and memory requirements.
- Updated `Config` to clarify the status of local agent usage.
- Refreshed `Package.resolved` and CI scripts to align with the new dependency versions.
…ities

- Introduced `swift-jinja` package with version 2.4.2 to project dependencies.
- Updated `LocalLLMService` to reflect that Gemma 4 models now support vision capabilities.
- Adjusted related tests to confirm the vision capability of Gemma 4 models.
- Enhanced model handling in `LocalLLMService` to ensure proper routing for vision tasks.
- Updated `LLMService` to conditionally skip tool instructions and adjust history management based on image data presence.
- Refined `LocalLLMService` to differentiate between photo and text turns, optimizing system prompts and history handling for multimodal interactions.
- Improved comments for clarity on the implications of multimodal processing and memory management.
…gement

- Introduced `otherStreamConsumersActive()` method to determine if other features are using the camera stream.
- Added `stopStreamUnlessShared()` method to manage camera streaming based on active features.
- Updated `saveToPhotoLibrary` and `saveVideoToPhotos` methods to utilize `GlassesPhotoAlbum` for album management, removing redundant album fetching logic.
- Cleaned up code by removing the now-unnecessary `fetchGlassesAlbum()` method from both `CameraService` and `VideoRecordingService`.
…ccess

- Removed redundant photo library access descriptions from Info.plist.
- Updated `CameraService` and `VideoRecordingService` to utilize the new `GlassesPhotoAlbum` methods for saving images and videos, simplifying the code and improving error handling.
- Enhanced `GlassesPhotoAlbum` with dedicated methods for saving images and videos, ensuring proper authorization checks and album management.
- Adjusted `DwellCaptureService` to use the new image saving method, improving code clarity and maintainability.
…aving logic

- Added a new usage description for saving photos to a dedicated Glasses album in the photo library.
- Refactored `GlassesPhotoAlbum` to improve authorization handling and streamline the image and video saving process.
- Updated methods to ensure proper album management and access permissions, enhancing user experience and code clarity.
- Simplified the authorization handling in `GlassesPhotoAlbum` by removing unnecessary parameters and streamlining the `ensureCanSave` method.
- Enhanced album management by introducing dedicated methods for fetching and creating albums, improving code clarity and maintainability.
- Updated image and video saving methods to utilize the new album management logic, ensuring a more efficient and user-friendly experience.

@straff2002 straff2002 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this — the Gemma 4 work is right, and I checked it against the checkpoint rather
than taking it on faith: tokenizer_config.json really does define sot_token = "<|turn>" /
eot_token = "<turn|>" with eos_token = "<eos>", and chat_template.jinja emits a genuine
system turn. So the hand-render is faithful and extraEOSTokens: ["<turn|>"] is genuinely
required, not belt-and-braces. The revision: pin with the "no tag carries #390" comment is
exactly the note I want on a pin like that.

Two mechanical blockers before anything else: the PR is CONFLICTING against main, and the
green test run predates main's tip, so it isn't evidence about the merged tree. Main landed
CameraStreamClaims (claim-based camera stream ownership) a few hours after your last commit,
which is where the conflict comes from.

The main ask

Reading through, a lot of this is one of two things welded together: something that helps
every user, and a workaround for the device you tested on. I want the first half of each,
and I want the second half kept but conditional — not applied to everyone. Three places:

1. Photos. The double permission prompt was caused by CameraService and
VideoRecordingService each carrying their own copy of the album code. Consolidating into
GlassesPhotoAlbum is the actual fix
, and it's a clean win — please keep it. Dropping to
add-only is a separate decision, and I think it costs everyone the Glasses album:
resolveAlbum() validates its cached identifier via PHAssetCollection.fetchAssetCollections,
which needs read access. Under add-only that fetch returns empty, so the cached ID is
discarded on every save, findAlbumByTitle() also returns nil, and createAlbum() runs again —
either a new empty "Glasses" album per photo, or no album at all. Could you check that on a
fresh install with add-only granted? If it reproduces, I'd rather keep requesting readWrite and
just request it once, in the one place you've now created.

2. Camera warmup. The lastStreamError early-abort is a real improvement for everyone — it
turns a 20 s hang into a fast fail, and it's the right read of that field log. But it also makes
the shortened timeout unnecessary: waitForStreaming(timeout: attempt == 1 ? 10 : 20) sits
below the cold-start window recorded in the comment three lines above it (~15–18 s of
.stopped/.waitingForDevice churn), so a healthy cold start now always fails attempt 1,
tears down, sleeps, and rebuilds. With your abort in place a dead start already fails fast on
its own, so healthy starts can keep the full 20 s. Your good idea removes the need for the other
one.

Same section: action(consecutiveFailures: attempt - 1) can only ever see 0, which is always
.rebuildStream — the resetSession() branch is dead.

3. Gemma memory pressure. Vision working is the universal win. Stripping history, tools and
the system prompt is a workaround for a device that's tight on RAM — but it's applied
unconditionally, so a 12 GB phone pays for an 8 GB phone's problem. There's already machinery
for this: LocalLLMService.marketingRAMGB / fitsDevice (used today only for the download
gate) and LocalModelBudget.promptBudget(for:). Routing the stripping through a RAM-aware
budget instead of hardcoding it would serve both devices.

Two specifics inside that one:

  • The sendLocal change (imageData == nil on tools + history) is redundant for Gemma 4 —
    generateGemma4VLMTurn already empties both downstream — so the only model whose behaviour
    actually changes is SmolVLM2, which doesn't have the unchunked-prefill problem. It's a
    straight loss for those users. Gate it on Gemma4ChatPrompt.matches or drop it.
  • generateGemma4VLMTurn hard-replaces the system prompt with an English literal on photo
    turns, so persona and language are dropped for non-English wearers every time they ask about
    a photo. If it stays, it should derive from the wearer's configured language and live next to
    the other prompts in Config.swift.

One question

What device did you test on? It decides a lot of the above. If you're on 8 GB running E2B,
the memory workarounds are real and should be tiered; if you're on 12 GB+ and stripped
defensively, they can probably just go. It also decides whether removing the "vision caveat"
from the model notes is honest for every user or only true on your handset.

Relatedly — could you confirm Qwen 2.5, SmolVLM2 and LFM2.5 still load on 14414441? That's
the pin's cost to users who'll never touch Gemma, and it's the one part of this that everybody
carries.

Would you split this?

The camera/Photos changes and the Gemma changes touch disjoint files. The Gemma half I'd merge
quickly once the above is settled; the camera half needs a rebase onto CameraStreamClaims
anyway. Two PRs would stop the good half waiting on the uncertain half.

On that rebase: AppState.otherStreamConsumersActive() / stopStreamUnlessShared() is a fourth
ad-hoc copy of the rule CameraStreamClaims was written to centralise, and it doesn't consult
cameraService.hasStreamClaims — so ending a turn would stop a stream continuous narration is
holding. Going through claimStream(for:) / releaseStream(for:) gets you the "don't stop what
you didn't start" behaviour for free. Also note stopStreamUnlessShared() is hooked into
returnToWakeWord(), which fires after every turn rather than at the end of a session — with
the 15–18 s cold start that's a full cold start per photo question, and it doesn't know about an
open Live Preview.

Smaller things

  • visionModelIds' doc comment says Gemma 4 text turns MUST go through Gemma4Processor.prepare,
    but generateGemma4VLMTurn hand-builds LMInput for text and its own inline comment says the
    opposite (nil setBytes → Metal assert). Same claim is now on LocalModelRoutingTests. One of
    them will walk the next reader into a crash.
  • ci_scripts/Package.resolved downgrades a pile of unrelated transitive deps (asn1 1.7→1.6,
    collections 1.5.1→1.4.1, crypto 4.5→4.3, nio 2.100→2.96, transformers 1.3.3→1.2.1) and drops
    the .git suffix from the swift-transformers URL, which no longer matches project.base.yml —
    Xcode Cloud may then ignore the pin entirely. Please regenerate with
    Scripts/update-package-resolved.sh rather than editing by hand.
  • swift-jinja is added as a direct dependency but nothing imports it, and Package.swift
    wasn't updated to match. If the exact 2.4.2 pin is what fixes the template parse, say so in
    the comment.
  • Please drop the Localizable.xcstrings churn — 1,461 lines, no view files changed, so it's all
    build extraction. CLAUDE.md asks for catalog updates on their own commit.
  • GlassesPhotoAlbum is the one genuinely pure, headless-testable piece here and has no tests.
    ensureCanSave also no longer accepts .limited, which the old code did.
  • Orphaned /// Name of the Photos album where recordings are saved. left above
    recordingTranscript in VideoRecordingService.
  • isJinjaParserFailure matches String(describing:) substrings, and its test uses a hand-rolled
    struct Fake: Error rather than a real Jinja error — it can't catch a change in the real error
    shape.

@exadeci

exadeci commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

@straff2002 Ok I'll look into fixing those, I do use an Iphone 15 Pro Max so 8GB ram.
The truth is that it's almost only AI work and I did max out my usage on Cursor so the model must have beeen downgraded which explains the drop in quality. I'll have to wait for my credits to renew before I can get it to fix it properly.

straff2002 added a commit that referenced this pull request Aug 25, 2026
…xtraction)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
straff2002 added a commit that referenced this pull request Aug 25, 2026
…nly, claim the warmup keepers

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@straff2002

Copy link
Copy Markdown
Owner

Closing this out with thanks — everything of value here has now landed on main, credited to you, re-composed onto the current tree rather than merged (the branch had drifted too far behind the camera/recording rework to rebase honestly).

Gemma — merged in 4b71b1f:

  • The load failure was fixed upstream (mlx-swift-lm Sync the string catalog with the sources (699 missing keys) #390); we now pin past it — d661402 rather than your 14414441, because the latter needs the Xcode 27 beta 5 SDK and doesn't compile on earlier betas. The pin comment says when to move it forward.
  • Your chat-template hand-render and extraEOSTokens: ["<turn|>"] are in essentially as you wrote them (both verified against the checkpoint), along with the parse-failure detection, the VLM turn path, and your Gemma4ChatPromptTests.
  • The memory-pressure stripping went in RAM-tiered (LocalModelBudget.multimodalTurnPlan) rather than unconditional; the sendLocal change was dropped (redundant for Gemma 4, a regression for SmolVLM2); the photo-turn prompt now derives from the wearer's configured language.
  • swift-jinja wasn't added as a direct dependency — 2.4.2 already resolves transitively and nothing imports it.

Photos + camera warmup — merged in 113bfe3:

  • Your GlassesPhotoAlbum consolidation is in — it really was the double-prompt fix — plus the cached-identifier resolution and the 3311 race handling. Authorization ships as readWrite-once: the add-only album-churn problem from the review is real (an add-only writer can't fetch the collection it needs), and it turned out main already had that bug — so your consolidation ended up fixing a live defect beyond the one you aimed at. The failure mode now ships as a test.
  • Your lastStreamError early-abort is in, with the full 20 s attempt-1 window restored (the shortened one sat under the ~15–18 s healthy cold start) — and the same shortened attempt was removed from capturePhoto, where it predated your PR. The dead resetSession() branch is fixed by moving escalation onto the shared failure counter.
  • The stream-sharing helpers weren't taken: CameraStreamClaims (landed just after your last push) covers that ground claim-based. The full hunk-by-hunk audit is in Ask for the photo library once, and let a healthy cold start finish (DI P1+P2) #346's description.

Really appreciate the contribution — the Gemma template work in particular shipped essentially as written. Sorry the merge conflict made this the long way round.

@exadeci

exadeci commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

@straff2002 Awesome thanks for sorting it out the regressions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants